package org.lq.ssm.controller;

import org.lq.ssm.Web.GetSession;
import org.lq.ssm.Web.HttpResult;
import org.lq.ssm.dto.PermissionDTO;
import org.lq.ssm.dto.RoleDTO;
import org.lq.ssm.dto.UserDTO;
import org.lq.ssm.service.UserService;
import org.lq.ssm.util.jwt.GeneralJwtToken;
import org.lq.ssm.util.MD5Encrypt;
import org.lq.ssm.util.jwt.claimsImp;
import org.lq.ssm.vo.LoginUserVO;
import org.lq.ssm.vo.mapper.LoginUserVOMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@RestController
public class LoginController {

    @Autowired
    UserService userService;

    //视图控制器的使用,在mvcconfig配置好之后，
    // 使用返回值为String的方法，返回的字符串即为所跳转的jsp页面的前缀名，
    //且控制器注解为@Controller
//    @RequestMapping("/")
//    public String login(){
//        return "index";
//    }

    @RequestMapping("/login")
    public HttpResult loginTo(@RequestParam(name = "username",defaultValue = "admin") String username, @RequestParam(name = "password",defaultValue = "123456") String password) throws IOException {
        UserDTO loginUser = userService.login(username, MD5Encrypt.MD5(password));
        List<String> permissionsName = userService.allRolesToPermissionName(loginUser);
        if (loginUser==null){
            return HttpResult.error(null,"用户名密码错误");
        }
        int level = 999;
        for (RoleDTO roleDTO : loginUser.getRole()){
            Integer newlevel = roleDTO.getLevel();
            if (level>newlevel){
                level=newlevel;
            }
        }
        HttpSession session = GetSession.getHttpSession();
        session.setAttribute("level",level);

        GeneralJwtToken generalJwtToken = new GeneralJwtToken("shj");
        claimsImp claimsImp = new claimsImp();
        claimsImp.setUserName(loginUser.getUsername());
        claimsImp.setLevel(level);
        String token = generalJwtToken.createToken(claimsImp);

        LoginUserVO loginUserVO = LoginUserVOMapper.INSTANCE.userDTOTOLoginUserVO(
                loginUser,
                loginUser.getDept().getName(),
                loginUser.getJob().getName(),
                permissionsName, token
        );
//        GetSession.getResponse().sendRedirect("/dashboard");
        return HttpResult.ok(loginUserVO,"登录成功,跳转到首页,登录等级为"+level);
    }

}
